# coding: utf-8

import re
import logging

from pyshoper.modules import BasePrice
from pyshoper.datadefs import Item
from urllib2 import urlopen
from urllib2 import URLError

class DNSShop(BasePrice):
    '''
    Переписанный модуль DNSShop.
    '''

    # Переопределение полей BasePrice
    __module_name__ = 'DNSShop'
    __description__ = 'Модуль парсинга прайса DNS.'

    # Статические.
    logger = logging.getLogger('pyshoper.modules.dnsmodule')
    price_link = 'http://samara.dns-shop.ru/catalog/{0}/'
    item_link = 'http://samara.dns-shop.ru/catalog/{0}/{1}/'

    sections = {
        'Computers and Accessories': {
            'Processors': '76'
        }
    }

    def run(self):
        for sectiontitle in self.sections:
            section = self.setbranch(sectiontitle)
            for categorytitle in self.sections.get(sectiontitle):
                category = self.setbranch(categorytitle, section)
                try:
                    page = self.importPage(
                        self.sections
                            .get(sectiontitle)
                            .get(categorytitle))
                except URLError, exception:
                    self.logger.error(
                            'Failed on downloading `{0}:{1}` price list '
                            'because of `{2}`'
                        .format(sectiontitle, categorytitle, exception))
                    continue
                items = self.getItems(page)
                for each in items:
                    category.add(self.getItem(
                        self.sections
                            .get(sectiontitle)
                            .get(categorytitle), each))


    def importPage(self, categoryId):
        raw = urlopen('http://samara.dns-shop.ru/catalog/{0!s}/'.format(categoryId))
        return raw.read().decode('utf-8')

    def getItems(self, page):
        regex = ur'<td class="c">(.*?)</td>'
        return list(int(x.group(1)) for x in re.finditer(regex, page))

    def getItem(self, categoryId, itemId):
        regex = ur'<td class="label">(.*?)</td><td>(.*?)</td>'
        raw = urlopen(
          'http://samara.dns-shop.ru/catalog/{0!s}/{1!s}/'
            .format(categoryId, itemId))
        page = raw.read().decode('utf-8')
        title = re.search(ur'<h1>(.*?)</h1>', page).group(1)
        item = Item(title)
        for each in re.finditer(regex, page):
            item.description.setdefault(each.group(1), each.group(2))
        item.description['price'] = int(
          re.search(ur'<span class="value">(.*?)</span>', page)
            .group(1)
            .replace(' ', ''))
        item.description['id'] = itemId
        return item
        